#include "pwm.h"
#include "driver/ledc.h"


void pwm_init(void)
{
    // 配置定时器
    ledc_timer_config_t ledc_cfg = {
        .speed_mode       = LEDC_LOW_SPEED_MODE,
        .duty_resolution  = LEDC_TIMER_10_BIT,
        .timer_num        = LEDC_TIMER_0,
        .freq_hz          = 5000,
        .clk_cfg          = LEDC_AUTO_CLK
    };
    ledc_timer_config(&ledc_cfg);

    // 配置通道
    ledc_channel_config_t channel_cfg = {
        .gpio_num       = GPIO_NUM_40,
        .speed_mode     = LEDC_LOW_SPEED_MODE,
        .channel        = LEDC_CHANNEL_0,
        .timer_sel      = LEDC_TIMER_0,
        .duty           = 0,
        .hpoint         = 0,
    };
    
    ledc_channel_config(&channel_cfg);
    
    
}

void pwm_set_duty(uint32_t duty){
    ledc_set_duty(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,duty);
    ledc_update_duty(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0);
}

void pwm_set_percent(uint8_t percent){
    uint32_t duty = (percent*1023)/100;
    pwm_set_duty(duty);
}
